package com.lingxinst.farm.base.widgets

import android.content.Context
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.os.CountDownTimer
import android.text.TextUtils
import android.util.AttributeSet
import android.view.Gravity
import android.view.View
import androidx.appcompat.widget.AppCompatButton
import androidx.core.content.withStyledAttributes
import com.lingxinst.farm.base.R

/**
 * Desc:   短信验证码倒计时按钮
 * Creator ling
 * Date:   2017/12/15 0015 17:15
 */
class TimerButton @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) :
    AppCompatButton(context, attrs, defStyleAttr), View.OnClickListener {

    private var countDownTimer: CountDownTimer? = null
    private var mOnClickListener: OnClickListener? = null
    private val DEFAULT_COUNT_SECOND = 61

    /**
     * 倒计时总时长，默认为60s
     */
    private var countSeconds = DEFAULT_COUNT_SECOND

    /**
     * 初始文本
     */
    private var normalText: String? = null

    /**
     * 倒计时文本
     */
    private var timerText: String? = null

    /**
     * 重新获取文本
     */
    private var againText: String? = null

    /**
     * Enable 状态下背景图片
     */
    private var enableBg: Drawable? = null

    /**
     * 非 Enable 装态下背景图片
     */
    private var unEnableBg: Drawable? = null

    /**
     * Enable 状态下背景颜色
     */
    private var enableBgColor = 0

    /**
     * 非 Enable 装态下背景颜色
     */
    private var unEnableBgColor = 0

    /**
     * Enable 状态下背景
     */
    private var enableTextColor = 0

    /**
     * 非 Enable 装态下背景
     */
    private var unEnableTextColor = 0

    /**
     * 是否自动倒计时，true：自动， false:手动
     */
    private var autoStart = false

    init {
        context.withStyledAttributes(attrs, R.styleable.TimerButton, defStyleAttr, 0) {

            countSeconds = getInteger(R.styleable.TimerButton_countSeconds, DEFAULT_COUNT_SECOND)

            normalText = getString(R.styleable.TimerButton_normalText)
            timerText = getString(R.styleable.TimerButton_timerText)
            againText = getString(R.styleable.TimerButton_againText)

            val background = background
            if (background == null) {
                enableBg = getDrawable(R.styleable.TimerButton_enableBg)
                unEnableBg = getDrawable(R.styleable.TimerButton_unEnableBg)

                // 此处需要判断，否则如果 enablebg != null 时，会报错
                if (enableBg == null) {
                    enableBgColor = getColor(R.styleable.TimerButton_enableBg, Color.TRANSPARENT)
                }
                if (unEnableBg == null) {
                    unEnableBgColor =
                        getColor(R.styleable.TimerButton_unEnableBg, Color.TRANSPARENT)
                }
            }

            enableTextColor = getColor(R.styleable.TimerButton_enableTextColor, 0)
            unEnableTextColor = getColor(R.styleable.TimerButton_unEnableTextColor, 0)

            autoStart = getBoolean(R.styleable.TimerButton_autoStart, false)

        }

        if (TextUtils.isEmpty(normalText)) normalText = ""
        if (TextUtils.isEmpty(timerText)) timerText = ""
        if (TextUtils.isEmpty(againText)) againText = ""
        text = normalText
        gravity = Gravity.CENTER

        update(isEnabled)

        setOnClickListener(this)

        if (autoStart) {
            start()
        }
    }

    override fun onClick(v: View) {
        if (mOnClickListener != null) {
            // 获取验证码
            mOnClickListener!!.onClick(this)
        }
    }


    fun setCountSeconds(countSeconds: Int): TimerButton {
        this.countSeconds = countSeconds
        return this
    }

    fun setNormalText(normalText: String?): TimerButton {
        this.normalText = normalText ?:""
        return this
    }

    fun setTimerText(timerText: String?): TimerButton {
        this.timerText = timerText ?:""
        return this
    }

    fun setAgainText(againText: String?): TimerButton {
        this.againText = againText?:""
        return this
    }

    fun setEnableBg(enableBg: Drawable?) {
        this.enableBg = enableBg
    }

    fun setUnEnableBg(unEnableBg: Drawable?) {
        this.unEnableBg = unEnableBg
    }

    fun setEnableBgColor(enableBgColor: Int) {
        this.enableBgColor = enableBgColor
    }

    fun setUnEnableBgColor(unEnableBgColor: Int) {
        this.unEnableBgColor = unEnableBgColor
    }

    fun setEnableTextColor(enableTextColor: Int) {
        this.enableTextColor = enableTextColor
    }

    fun setUnEnableTextColor(unEnableTextColor: Int) {
        this.unEnableTextColor = unEnableTextColor
    }

    fun setAutoStart(autoStart: Boolean) {
        this.autoStart = autoStart
    }

    /**
     * 开启倒计时
     */
    fun start() {
        isEnabled = false
        countDownTimer = object : CountDownTimer((countSeconds * 1000).toLong(), 1000) {
            override fun onTick(millisUntilFinished: Long) {
                val showTime = millisUntilFinished / 1000
                // 一般来说，倒计时文字 是一串文字，这里使用格式化字符串
                text = String.format(timerText!!, showTime)
            }

            override fun onFinish() {
                resetButton()
            }
        }

        countDownTimer?.start()

        update(isEnabled)
    }

    /**
     * 停止倒计时
     */
    private fun stop() {
        if (countDownTimer != null) {
            countDownTimer!!.cancel()
        }
        resetButton()
    }

    private fun resetButton() {
        isEnabled = true
        text = againText
        update(isEnabled)
    }

// This function updates the background, background color, and text color of a view based on whether it is enabled or not
    private fun update(isEnable: Boolean) {
        // If the view is enabled
        if (isEnable) {
            // If the enable background is not null, set the background drawable to the enable background
            if (enableBg != null) {
                setBackgroundDrawable(enableBg)
            }

            // If the enable background color is not 0, set the background color to the enable background color
            if (enableBgColor != 0) {
                setBackgroundColor(enableBgColor)
            }

            // If the enable text color is not 0, set the text color to the enable text color
            if (enableTextColor != 0) {
                setTextColor(enableTextColor)
            }
        // If the view is not enabled
        } else {
            // If the unenable background is not null, set the background drawable to the unenable background
            if (unEnableBg != null) {
                setBackgroundDrawable(unEnableBg)
            }

            // If the unenable background color is not 0, set the background color to the unenable background color
            if (unEnableBgColor != 0) {
                setBackgroundColor(unEnableBgColor)
            }

            // If the unenable text color is not 0, set the text color to the unenable text color
            if (unEnableTextColor != 0) {
                setTextColor(unEnableTextColor)
            }
        }
    }


    interface OnClickListener {
        fun onClick(v: View?)
    }

    fun setOnClickListener(listener: OnClickListener?): TimerButton {
        mOnClickListener = listener
        return this
    }
}
